<?php

namespace App\Http\Controllers\Wap;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\TraitClass\PassportProxyTrait;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

/**
 * app接入层控制器
 * @author  thinkpanax <thinkpanax@163.com>
 */

class AccessController extends BaseController
{

    use PassportProxyTrait, AuthenticatesUsers;

    /**
     * 架构初始化
     */
    public function __construct()
    {
        parent::__construct();
        //
        $this->middleware("wap_auth")->only(['logout']);
    }
    /**
     * 登录
     *
     * @return \Illuminate\Http\Response
     */
    public function login(Request $Request)
    {
        //
        $request_params = $Request->only(['username', 'password']);
        $rules = [
            'username' => 'required',
            'password' => 'required',
        ];

        $validator = Validator::make($request_params, $rules);
        if ($validator->fails()) {
            $res_msg = $validator->errors()->first();
            return $this->returnErrorApi($res_msg);
        }

        if ($this->hasTooManyLoginAttempts($Request)) {
            $this->fireLockoutEvent($Request);

            return $this->returnErrorApi('您登录的次数过多，无法再登录');
        }

        $result = $this->authenticate('wap', $request_params['username'], $request_params['password']);
        if (false === $result) {
            # code...
            return $this->returnErrorApi('账号密码错误！');
        }

        return $this->returnOkApi('登录成功', $result);

    }

    /**
     * 登录显示
     *
     * @return void
     */
    public function loginTip()
    {
        return $this->returnErrorApi('未授权，请登录后重试！', null, 30001);
    }
    /**
     * 注销
     *
     * @return void
     */
    public function logout()
    {
        $guard = 'wap';
        if (\Auth::guard($guard)->check()) {

            \Auth::guard($guard)->user()->token()->delete();
        }

        return $this->returnOkApi('注销成功。');
    }
    /**
     * 刷新token
     *
     * @return void
     */
    public function refreshToken(Request $request)
    {
        $request_params = $request->only('refresh_token');
        $rules = [
            'refresh_token' => 'required',
        ];
        $validator = Validator::make($request_params, $rules);
        if ($validator->fails()) {
            # code...
            $error_msg = $validator->errors()->first();
            return $this->returnErrorApi($error_msg);
        }

        $tokens = $this->getRefreshtoken($request_params['refresh_token']);
        if (false === $tokens) {
            # code...
            return $this->returnErrorApi("refresh_token错误或失效！");
        }

        return $this->returnApi(20000, '成功刷新', $tokens);

    }

}
